package _interview150;

import java.util.ArrayList;
import java.util.List;

/**
 * 54. 螺旋矩阵
 */
public class No54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<>();
        int left = 0, right = matrix[0].length - 1, top = 0, button = matrix.length - 1;
        while (true) {
            // 左到右
            for (int i = left; i <= right; i++) ans.add(matrix[top][i]);
            if (++top > button) break;
            // 上到下
            for (int i = top; i <= button; i++) ans.add(matrix[i][right]);
            if (--right < left) break;
            // 右到左
            for (int i = right; i >= left; i--) ans.add(matrix[button][i]);
            if (--button < top) break;
            // 下到上
            for (int i = button; i >= top; i--) ans.add(matrix[i][left]);
            if (++left > right) break;
        }
        return ans;
    }
}
